package com.mall.util.distributed.raft.pool;

import lombok.var;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class RaftThreadPool {
    private static final int CUP_CORE = Runtime.getRuntime().availableProcessors();
    private static final int MAX_CPU_MAX = CUP_CORE * 2;
    private static final int QUEUE_SIZE = 1024;
    private static final long KEEP_TIME = 1000 * 60;
    private static final TimeUnit KEEP_TIME_UNIT = TimeUnit.MILLISECONDS;

    public static ThreadPoolExecutor getThreadPool() {
        return new ThreadPoolExecutor(
                CUP_CORE,
                MAX_CPU_MAX,
                KEEP_TIME,
                KEEP_TIME_UNIT,
                new LinkedBlockingQueue<Runnable>(QUEUE_SIZE),
                new NameThreadFactory());
    }

    public static ScheduledExecutorService getScheduled() {
        return new ScheduledThreadPoolExecutor(CUP_CORE, new NameThreadFactory());
    }

    static class NameThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        NameThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        @Override
        public Thread newThread(Runnable runnable) {
            var thread = new Thread(group, runnable,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            thread.setDaemon(true);
            thread.setPriority(5);
            return thread;
        }
    }
}
